package docker

import (
	"html/template"
	"os"
	"os/exec"
	"path/filepath"

	"gitee.com/extrame/fb-runner/util"
	"gitee.com/extrame/fb-runner/version"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

func Create(v version.Version, source, base, networkName string, useCouchdb bool) error {

	var cfgs = []string{"docker/docker-compose-test-net.yaml"}

	if useCouchdb {
		cfgs = append(cfgs, "docker/docker-compose-couch.yaml")
	}

	for _, c := range cfgs {
		err := copyTemplate(v, source, base, networkName, c)
		if err != nil {
			return errors.Wrap(err, "in copy from template")
		}
	}

	return nil
}

func Run(base, networkName string, useCouchdb bool) error {

	var cfgs = []string{"docker/docker-compose-test-net.yaml"}

	if useCouchdb {
		cfgs = append(cfgs, "docker/docker-compose-couch.yaml")
	}

	var args []string

	for _, c := range cfgs {
		args = append(args, "-f", c)
	}

	args = append(args, "-p", networkName, "up", "-d")

	cmd := exec.Command("docker-compose", args...)
	cmd.Dir = base
	_, _, err := util.Run(cmd, true)
	return err
}

func Stop(base string, network string, removeVolume bool) error {

	// util.Mkdir(filepath.Join(base, "/organizations/fabric-ca/org1"))
	// util.Mkdir(filepath.Join(base, "/organizations/fabric-ca/org2"))
	// util.Mkdir(filepath.Join(base, "/organizations/fabric-ca/order"))
	// copy docker-compose file

	var cfgs = []string{"docker/docker-compose-test-net.yaml", "docker/docker-compose-couch.yaml", "docker/docker-compose-ca.yaml"}

	var args []string

	for _, c := range cfgs {
		fullName := filepath.Join(base, c)
		if _, err := os.Stat(fullName); err == nil {
			//避免启动过程中有不成功的步骤
			args = append(args, "-f", fullName)
		} else {
			logrus.Errorln(fullName, "is not exists,ignored")
		}
	}

	args = append(args, "-p", network, "down", "--remove-orphans")

	if removeVolume {
		logrus.Errorln("当前模式为非持续模式，所有数据将会删除，请在配置中配置persist=true避免该问题")
		args = append(args, "--volumes")
	}

	cmd := exec.Command("docker-compose", args...)
	// absBase, _ := filepath.Abs(base)
	// cmd.Dir = absBase
	_, _, err := util.Run(cmd, true)
	return err
}

func copyTemplate(v version.Version, source, base, networkName, name string) error {
	t, err := template.New(filepath.Base(name)).Funcs(template.FuncMap{
		"extendPort": func(base int, i int) int {
			return base + i*2000
		},
		"increase": func(i int) int {
			return i + 1
		},
	}).ParseFiles(filepath.Join(source, name))
	if err == nil {
		var f *os.File
		util.MkdirFor(filepath.Join(base, name))
		f, err = os.OpenFile(filepath.Join(base, name), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
		logrus.Infoln("创建配置文件", filepath.Join(base, name))
		if err == nil {
			data := make(map[string]interface{})
			data["ImageTag"] = string(v)
			data["NetworkName"] = networkName
			data["Organizations"] = util.Config.Organizations
			err = t.Execute(f, data)
			f.Close()
		}
	}
	return err
}
